package cn.clq.ssmshiro.service;

import cn.clq.ssmshiro.dao.ItemsDao;
import cn.clq.ssmshiro.pojo.Items;
import cn.clq.ssmshiro.pojo.User;
import cn.clq.ssmshiro.util.JedisUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.util.SerializationUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ItemService {

    private static final String ITEMS_PROFIX = "items_cache:";
    public static final ObjectMapper mapper = new ObjectMapper();
    @Resource
    private ItemsDao itemsDao;
    @Resource
    private JedisUtil jedisUtil;


    public List<Items> findAllItems() {
//        System.out.println(session.getId());
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute("user");
        byte[] value = jedisUtil.get(getKey(user.getUsername()));
        if (value == null) {
            System.out.println("从数据库中读取");
            List<Items> items = itemsDao.getItems();
            jedisUtil.set(getKey(user.getUsername()), SerializationUtils.serialize(items.toString()));
            jedisUtil.expire(getKey(user.getUsername()),600);
            return items;
        } else {
            System.out.println("从Redis缓存中读取");
            ObjectMapper mapper = new ObjectMapper();
            JavaType javaType = getCollectionType(ArrayList.class, Items.class);
            System.out.println((String) SerializationUtils.deserialize(value));
            try {
                List<Items> list = mapper.readValue((String) SerializationUtils.deserialize(value), javaType);
                return list;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }
    private byte[] getKey(String username) {
        return (ITEMS_PROFIX+username).getBytes();
    }
}
